<?php

// +----------------------------------------------------------------------
// | EasyAdmin
// +----------------------------------------------------------------------
// | PHP交流群: 763822524
// +----------------------------------------------------------------------
// | 开源协议  https://mit-license.org 
// +----------------------------------------------------------------------
// | github开源项目：https://github.com/zhongshaofa/EasyAdmin
// +----------------------------------------------------------------------

namespace app\admin\controller\system;


use app\admin\model\website\Robots;

//用户组表
use app\admin\model\website\UserGroup as UserGroupModel;
//房间号
use app\admin\model\website\Rooms as RoomsModel;

use app\common\controller\AdminController;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;

use Exception;
use think\App;
use think\facade\Db;

/**
 * Class Admin
 * @package app\admin\controller\system
 * @ControllerAnnotation(title="IP封禁")
 */
class RobotsList extends AdminController
{

    use \app\admin\traits\Curd;

    protected $sort = [
        'id'   => 'desc',
    ];

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new Robots();
    }

    /**
     * @NodeAnotation(title="列表")
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames();
        
            
            $countModel = $this->model->where($where);
            if (session("admin.group") != 1) {
                $countModel->where("operator",session("admin.username"));
            }
            $count = $countModel->count();
            $listModel = $this->model->where($where);
            if (session("admin.group") != 1) {
                $listModel->where("operator",session("admin.username"));
            }
            $list = $listModel->page($page, $limit)
                ->order($this->sort)
                ->select();
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="添加")
     */
    public function add()
    {   
        $this->getAuth();
        if ($this->request->isAjax()) {
            $post = $this->request->post();

            $post['operator'] = session("admin.username");
            if (!isset($post['rid'])) {
                $post['rid'] = session("admin.rooms");
            }else{
                if ($post['rid'] == '') {
                    $post['rid'] = session("admin.rooms");
                }
            }

            if (!isset($post['gid'])) {
                $post['gid'] = 3;
            }else {
                if ($post['gid'] == '') {
                    $post['gid'] = 3;
                }
            }
            
            try {
                $save = $this->model->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }

        return $this->fetch();
    }


    /**
     * @NodeAnotation(title="删除")
     */
    public function delete($id)
    {
        $row = $this->model->whereIn('id', $id)->select();
        $row->isEmpty() && $this->error('数据不存在');
        
        try {
            $save = $row->delete();
        } catch (\Exception $e) {
            $this->error('删除失败');
        }
        $save ? $this->success('删除成功') : $this->error('删除失败');
    }

    // 获取用户组
    public function getAuth()
    {
        //获取用户组
        if (session("admin.group") == 1) {
            $rules = "1,857";
        }else if(session("admin.group") == 5) {
            $rules = "1,857,4";
        }else{
            $rules = "1,857,6,4,5";
        }
        $groups = UserGroupModel::where('id','not in',$rules)->select()->toArray();
        $groupList = array();
        $i=0;
        foreach($groups as $value) {
            $groupList[$i]['value'] = $value['id'];
            $groupList[$i]['label'] = $value['name'];
            $i++;
        }

        $this->assign("groups",$groupList);

        //获取房间号
        $where = array();
        if (session("admin.group") == 5) {
            $where['roomid'] = ['in',session("rooms")];
        }
        $rooms = RoomsModel::field("roomid")->where($where)->select()->toArray();
        $this->assign("rooms",$rooms);
    }
    /**
     * @NodeAnotation(title="编辑")
     */
    public function edit($id)
    {
        $this->getAuth();
        $row = $this->model->find($id);
        empty($row) && $this->error('数据不存在');
        if ($this->request->isAjax()) {
            $post = $this->request->post();

            if (!isset($post['rid'])) {
                $post['rid'] = session("admin.rooms");
            }else{
                if ($post['rid'] == '') {
                    $post['rid'] = session("admin.rooms");
                }
            }

            if (!isset($post['gid'])) {
                $post['gid'] = 3;
            }else {
                if ($post['gid'] == '') {
                    $post['gid'] = 3;
                }
            }
            

            try {
                $save = $row->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        $row->rooms = explode(",",$row->rooms);
        $this->assign('row', $row);
        return $this->fetch();
    }


     //导入
     public function robotimport()
     {   
         $file = request()->file('file');
         $list = importinfo($file);
         $mysqlArray = array();
         foreach ($list as $value) {
             //判断用户名是否存在
                 $item = array();
                 $item['name'] = $value[0];
                 if (!$item['name']) {
                    continue;
                }
                 //处理基础数据
                 $item['create_time'] = time();
                 $item['operator'] = session("admin.username");
                 $item['gid'] = 3;
                 $item['rid'] = session("admin.rooms");
                 $mysqlArray[] = $item;
         }
 
         $useAll = array_column($mysqlArray, 'name');
         $repeatUser = Robots::where("name",'in',$useAll)->column('name');
         $match = array();
         foreach ($repeatUser as  $value) {
            $value = trim($value);
            if (array_search(strtolower($value), $useAll)) {
                $value = array_search(strtolower($value), $useAll);
            } else if (array_search(strtoupper($value), $useAll)) {
                $value = array_search(strtoupper($value), $useAll);
            } else {
                $value = array_search($value, $useAll);
            }
            if ($value)
                $match[] = $value;
         }
 
         foreach ($match as $value) {
             unset($mysqlArray[$value]);
         }
 
         try{
             $userModel = new Robots;
             $res = $userModel->saveAll($mysqlArray);
             return $res ? app("json")->success("导入成功",$repeatUser) : app("json")->fail("导入失败");
         }catch (Exception $e) {
             return app("json")->fail("导入失败");
         }
         
     }   
 
     //批量创建 
     public function addrobot () 
     {
         $this->getAuth();
         if ($this->request->isAjax() || !empty($_GET)) {
             $post = $this->request->post();
             if (empty($post)) $post = $_GET;
             if ($post['startsuffix']>$post['endsuffix']) {
                 return $this->error('后缀的开始数字不能大于结束数字');
             }
 
             if ((int)$post['endsuffix'] - (int)$post['startsuffix'] > 500) {
                 $post['endsuffix'] = (int)$post['startsuffix'] + 500;
             }
 
             $userList = array();
 
             for ($i = (int)$post['startsuffix'];$i <= (int)$post['endsuffix'];$i++) {
 
                    $item = array();
                    $item['name'] = $post['prefix'].$i;
                     
                    $item['create_time'] = time();
                    $item['operator'] = session("admin.username");
                    $item['gid'] = 3;
                    $item['rid'] = isset($post['rooms']) ? $post['rooms'] : session("admin.rooms");
                    $userList[] = $item;
             }
             $useAll = array_column($userList, 'name');
             $repeatUser = Robots::where("name",'in',$useAll)->column('name');
 
             $match = array();
 
             foreach ($repeatUser as  $value) {
                $value = trim($value);
                if (array_search(strtolower($value), $useAll)) {
                    $value = array_search(strtolower($value), $useAll);
                } else if (array_search(strtoupper($value), $useAll)) {
                    $value = array_search(strtoupper($value), $useAll);
                } else {
                    $value = array_search($value, $useAll);
                }
                if ($value)
                    $match[] = $value;
             }
 
 
             foreach ($match as $value) {
                 unset($userList[$value]);
             }
             
             try{
                 $userModel = new Robots;
                 $userModel->saveAll($userList);
             }catch (Exception $e) {
                
             }
             $this->success("添加成功");
 
         }
         return $this->fetch();
     }



     

}
